import 'base_chart.dart';
import 'package:flutter/material.dart';
import 'extensions/extension-china-map.dart';
import 'package:ribo_base_core/base_models/base_chart_model.dart';
import 'package:ribo_base_core/base_models/base_chart_china_map_model.dart';

class BaseChartChinaMap extends StatefulWidget {

  BaseChartChinaMap({Key key, @required this.model}) : super(key: key);

  final BaseChartChinaMapModel model;

  @override
  _BaseChartChinaMapState createState() => _BaseChartChinaMapState();

}

class _BaseChartChinaMapState extends State<BaseChartChinaMap> {

  Map<String, dynamic> _option;

  @override
  Widget build(BuildContext context) {
    _handleModel();
    String name = widget.model?.name??'china';
    String code = widget.model?.code??'100000';
    return FutureBuilder<String>(
      future: ExtensionChinaMap.registerMapByCode(name,code),
      builder: (BuildContext context, AsyncSnapshot<String> snapshot) {
        if (snapshot.hasData) {
          return Column(
            children: [
              Expanded(child: BaseChart(model: BaseChartModel(style: widget.model?.style, option: this._option, extensions: [snapshot.data], extraScript: '''
  chart.getZr().on('click', (params) => {
    if ( params.target ) {
       return;
    } else { 
       chart.dispatchAction({ type:'select', dataIndex: -1 });
    }
  });
''' ), )),
              _buildFooterWidget(),
            ],
          );
        }
        return Container();
    });
  }

  Widget _buildFooterWidget() {
    List<BaseChartPiecesData> pieces = widget.model?.pieces;
    if ( pieces == null || pieces.length == 0 ) {
      return SizedBox();
    }
    return _buildFooterContentWidget( pieces );
  }

  Widget _buildFooterContentWidget( List<BaseChartPiecesData> pieces ) {
    return Container(child: _buildVisualMapWidget( pieces ), padding: const EdgeInsets.symmetric( horizontal: 8.0 ),);
  }

  Widget _buildVisualMapWidget( List<BaseChartPiecesData> pieces ) {
    return Row(
      mainAxisAlignment: MainAxisAlignment.spaceBetween,
      children: [
        ...pieces.map((e) => _buildVisualMapItemWidget(e)).toList(),
      ]
    );
  }

  Widget _buildVisualMapItemWidget( BaseChartPiecesData data ) {
    return Row(
      children: [
        Container( height: 10.0, width: 10.0, decoration: BoxDecoration(borderRadius: BorderRadius.all(Radius.circular(10)), color: _transformColor( data.color )), margin: const EdgeInsets.only( right: 4.0 ), ),
        Text( data.label, style: Theme.of(context).textTheme.bodyText2.copyWith( fontSize: 12.0 ) ),
      ],
    );
  }

  /// 字符串变color
  Color _transformColor(String hexColor) {
    hexColor = hexColor.toUpperCase().replaceAll("#", "");
    hexColor = hexColor.replaceAll('0X', '');
    if (hexColor.length == 6) {
      hexColor = "FF" + hexColor;
    }
    return Color(int.parse(hexColor, radix: 16));
  }

  void _handleModel() {
    this._option = {
      'tooltip': {'trigger': 'item', 'position': [10,10], 'formatter': widget.model?.tooltipFormatter?.toJson()},
      'visualMap': {
        'type': 'piecewise',
        'splitNumber': widget.model?.pieces?.length,
        'pieces': widget.model?.pieces?.map((e) => e.toJson())?.toList(),
        'textStyle': {
          'fontSize': 12
        },
        'text': widget.model.visualMapTexts,
        'textGap': 4,
        'itemGap': 6,
        'itemHeight': 10,
        'itemWidth': 10,
        'itemSymbol': 'circle',
        'showLabel': true,
        'left': 'center',
        'top': 'bottom',
        'show': false
      },
      'series': [
          {
          'type': 'map',
          'map': widget.model?.name??'china',
          'zoom': 1.2,
          'roam': widget.model?.roam,
          'top': 'middle',
          'showLegendSymbol': false,
          'label': {'show': false, 'emphasis': {'show': true},
            "position": 'center',
            "textStyle": {"color": '#800080'},
            "fontSize": 6,
            'formatter': widget.model?.labelFormatter?.toJson()
          },
          'itemStyle': {'areaColor': '#fff'},
          'nameProperty': 'id',
          'data': widget.model?.data?.map((e) => e.toJson())?.toList(),
        },
      ],
    };
  }

}
